<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\CategoryService;
use App\Http\Requests\Admin\CategoryRequest;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class CategoryController extends Controller
{
    protected CategoryService $categoryService;

    public function __construct(CategoryService $categoryService)
    {
        $this->categoryService = $categoryService;
    }

    /**
     * 显示分类管理页面
     */
    public function index(Request $request): View
    {
        $perPage = 20;
        $search = $request->get('search');
        $status = $request->get('status');
        $sort = $request->get('sort', 'sort_order');

        if ($search) {
            $categories = $this->categoryService->searchCategories($search, $perPage);
        } elseif ($status !== null) {
            $categories = $this->categoryService->getCategoriesByStatus((bool)$status, $perPage);
        } else {
            $categories = $this->categoryService->getCategories($perPage);
        }
        
        $stats = $this->categoryService->getCategoryStats();
        
        return view('admin.categories.index', compact('categories', 'stats'));
    }

    /**
     * 显示创建分类页面
     */
    public function create(): View
    {
        return view('admin.categories.create');
    }

    /**
     * 显示编辑分类页面
     */
    public function edit(int $id): View
    {
        $category = $this->categoryService->getCategoryById($id);
        
        // 获取该分类下的所有菜品
        $dishes = $category->dishes()->with('category')->orderBy('sort_order')->orderBy('created_at', 'desc')->get();
        
        return view('admin.categories.edit', compact('category', 'dishes'));
    }

    /**
     * 获取分类列表API
     */
    public function list(Request $request): JsonResponse
    {
        $perPage = $request->get('per_page', 20);
        $search = $request->get('search');
        $status = $request->get('status');

        if ($search) {
            $categories = $this->categoryService->searchCategories($search, $perPage);
        } elseif ($status !== null) {
            $categories = $this->categoryService->getCategoriesByStatus((bool)$status, $perPage);
        } else {
            $categories = $this->categoryService->getCategories($perPage);
        }

        return response()->json([
            'success' => true,
            'data' => $categories->items(),
            'pagination' => [
                'current_page' => $categories->currentPage(),
                'last_page' => $categories->lastPage(),
                'per_page' => $categories->perPage(),
                'total' => $categories->total(),
            ]
        ]);
    }

    /**
     * 获取所有分类（不分页）
     */
    public function all(): JsonResponse
    {
        $categories = $this->categoryService->getAllCategories();

        return response()->json([
            'success' => true,
            'data' => $categories
        ]);
    }

    /**
     * 显示分类详情页面
     */
    public function show(int $id)
    {
        $category = $this->categoryService->getCategoryById($id);
        
        // 获取该分类下的所有菜品
        $dishes = $category->dishes()->with('category')->orderBy('sort_order')->orderBy('created_at', 'desc')->get();
        
        // 如果是API请求，返回JSON
        if (request()->expectsJson()) {
            return response()->json([
                'success' => true,
                'data' => $category
            ]);
        }
        
        // 否则返回视图
        return view('admin.categories.show', compact('category', 'dishes'));
    }

    /**
     * 创建分类
     */
    public function store(CategoryRequest $request)
    {
        $category = $this->categoryService->createCategory($request->validated());

        // 记录详细的操作日志
        activity()
            ->causedBy(auth()->user())
            ->performedOn($category)
            ->withProperties([
                'action' => 'create',
                'data' => $request->validated(),
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log('创建了新的分类：' . $category->name);

        return redirect()->route('admin.categories.index')
            ->with('success', '分类创建成功！');
    }

    /**
     * 更新分类
     */
    public function update(CategoryRequest $request, int $id)
    {
        $category = $this->categoryService->updateCategory($id, $request->validated());

        // 记录详细的操作日志
        activity()
            ->causedBy(auth()->user())
            ->performedOn($category)
            ->withProperties([
                'action' => 'update',
                'data' => $request->validated(),
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log('更新了分类：' . $category->name);

        return redirect()->route('admin.categories.index')
            ->with('success', '分类更新成功！');
    }

    /**
     * 删除分类
     */
    public function destroy(int $id)
    {
        try {
            $this->categoryService->deleteCategory($id);

            return redirect()->route('admin.categories.index')
                ->with('success', '分类删除成功！');
        } catch (\Exception $e) {
            return redirect()->route('admin.categories.index')
                ->with('error', $e->getMessage());
        }
    }

    /**
     * 切换分类状态
     */
    public function toggleStatus(int $id)
    {
        $category = $this->categoryService->toggleCategoryStatus($id);
        $status = $category->is_active ? '启用' : '禁用';

        return redirect()->route('admin.categories.index')
            ->with('success', "分类已{$status}！");
    }

    /**
     * 获取分类统计信息
     */
    public function stats(): JsonResponse
    {
        $stats = $this->categoryService->getCategoryStats();

        return response()->json([
            'success' => true,
            'data' => $stats
        ]);
    }
}